# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.addons.mxnet_base.dysms_python import demo_sms_send
import uuid, random, datetime

class PhoneVerifyWizard(models.TransientModel):
    _name = "phone.verify.wizard"
    _description = u'电话验证'

    phone = fields.Char(string=u'电话')
    code = fields.Char(string=u'验证码')

    @api.model
    def send_verify_code(self, phone):
        '''发送验证码'''
        # 检查该手机号是否已验证过
        code = random.randint(1000, 9999)
        params = "{\"code\":\"%d\"}" % code
        try:
            result = demo_sms_send.send_sms(uuid.uuid1(), phone, u"敏行网络", "SMS_135310207", params)
        except Exception,e:
            return {
                'success': False,
                'msg': e.message,
            }
        result = eval(result)
        if result.get('Message') != 'OK':
            return {
                'success': False,
                'msg': result.get('Message'),
            }
        # 创建记录
        records = self.search([
            ('phone', '=', phone),
            ('code', '=', code)
        ])
        if records:
            records.unlink()
        self.create({
            'phone': phone,
            'code': code,
        })
        return {'success': True}

    # @api.model
    # def send_verify_code(self, phone):
    #     '''发送验证码'''
    #     # 检查该手机号是否已验证过
    #     code = random.randint(1000, 9999)
    #     params = "{\"code\":\"%d\"}" % code
    #     result = demo_sms_send.send_sms(uuid.uuid1(), phone, u"艾格绿环保科技", "SMS_137840156", params)
    #     result = eval(result)
    #     print result
    #     if result.get('Message') != 'OK':
    #         raise UserError(result.get('Message'))

    @api.model
    def check_mobile_verify_code(self, phone, code):
        '''验证手机验证码'''
        record = self.search([
            ('phone', '=', phone),
            ('code', '=', code),
        ], limit=1)
        if not record:
            return {
                'success': False,
                'msg': u'验证码错误！',
            }
        now_time = datetime.datetime.now()
        send_time = datetime.datetime.strptime(record.create_date, "%Y-%m-%d %H:%M:%S")
        if now_time - datetime.timedelta(minutes=5) > send_time:
            return {
                'success': False,
                'msg': u'验证码超时！',
            }
        return {'success': True}
